import { login, getMenu, logout, chanPwd, getAuthority, refreshToken, getMenuAuthority, getVerification, checkVerification, editPassword } from '@/api/userApi'
import { reject } from 'lodash'
const user = {
  namespaced: true,
  state: {
    userInfo: JSON.parse(sessionStorage.getItem('userInfo')) || {},
    role: sessionStorage.getItem('role') || '',
    token: sessionStorage.getItem('token') || '',
    refreshToken: sessionStorage.getItem('refreshToken') || '',
    menu: [],
    permission: JSON.parse(sessionStorage.getItem('permission')) || [],
    codeKey: -1, // 验证码key
    pwdExpireDay: null

  },
  getters: {},
  mutations: {
    SET_TOKEN: (state, params) => {
      state.token = params
      sessionStorage.setItem('token', params)
    },
    SET_REFRESH_TOKEN: (state, params) => {
      state.refreshToken = params
      sessionStorage.setItem('refreshToken', params)
    },
    SET_MENU: (state, params) => {
      state.menu = params
      // sessionStorage.setItem('menu', JSON.stringify(params))
    },
    SET_ROLE: (state, params) => {
      state.role = params
      sessionStorage.setItem('role', params)
    },
    SET_PERMISSION: (state, params) => {
      state.permission = params
      sessionStorage.setItem('permission', JSON.stringify(params))
    },
    SET_USER_INFO: (state, params) => {
      state.userInfo = params
      sessionStorage.setItem('userInfo', JSON.stringify(params))
    },
    SET_CODE_KEY: (state, params) => {
      state.codeKey = params
    },
    SET_PWDEXPIREDAY: (state, params) => {
      state.pwdExpireDay = params
    }
  },
  actions: {
    Login ({ state, commit, dispatch }, params) {
      return new Promise((resolve, reject) => {
        login(params).then(res => {
          // 登录成功，存入token、role（自定义的一个值）、userinfo
          if (res.code == 200) {
            // console.log(res.data)
            commit('SET_TOKEN', res.data.accessToken)
            // commit('SET_REFRESH_TOKEN', res.data.refreshToken)
            commit('SET_ROLE', res.data.permission)

            commit('SET_PERMISSION', res.data.userAuthority)

            commit('SET_USER_INFO', res.data)
          }
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    Logout ({ state, commit, dispatch }, params) {
      return new Promise((resolve, reject) => {
        logout(params).then(res => {
          commit('SET_TOKEN', '')
          commit('SET_ROLE', '')
          commit('SET_PERMISSION', [])
          commit('SET_USER_INFO', {})
          resolve(res)
        })
      })
    },
    RefreshToken ({ state, commit, dispatch }, params) {
      return new Promise((resolve, reject) => {
        refreshToken(params).then(res => {
          // 登录成功，存入token、role（自定义的一个值）、userinfo
          if (res.code == 200) {
            commit('SET_TOKEN', res.data.accessToken)
            commit('SET_REFRESH_TOKEN', res.data.refreshToken)
          }
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    ChanPwd ({ state, commit, dispatch }, params) {
      return new Promise((resolve, reject) => {
        chanPwd(params).then(res => {
          resolve(res)
        })
      })
    },
    GetMenu ({state, commit, dispatch}, params) {
        return new Promise((resolve, reject) => {
            var role = state.role == 'all' ? 'admin' : 'user'
            getMenu(role).then(res => {              
                commit('SET_MENU', res.data)
                resolve(res)
            })
        })
    },
    GetAuthority ({ state, commit, dispatch }, params) {
      return new Promise((resolve, reject) => {
        getAuthority(params).then(res => {
          resolve(res)
        })
      })
    },
    GetMenuAuthority ({ state, commit, dispatch }, params) {
      return new Promise((resolve, reject) => {
        params = state.permission
        // console.log(params)
        getMenuAuthority(params).then(res => {
          commit('SET_MENU', res.data)
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 将菜单列表扁平化形成权限列表
    GetPermissionList ({ state, commit, dispatch }) {
      return new Promise((resolve, reject) => {
        let permissionList = []
        // 将菜单数据扁平化为一级
        function flatNavList (arr) {
          for (let v of arr) {
            permissionList.push(v)
          }
        }
        dispatch('GetMenuAuthority').then(res => {
          flatNavList(state.menu)
          resolve(permissionList)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 获取验证码
    GetVerification ({ state, commit, dispatch }, params) {
      return new Promise((resolve, reject) => {
        getVerification(params).then(res => {
          if (res.code == 200) {

          }
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    //  校验验证码
    CheckVerification ({ state, commit, dispatch }, params) {
      return new Promise((resolve, reject) => {
        checkVerification(params).then(res => {
          if (res.code == 200) {

          }
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 修改密码
    EditPassword ({state, commit, dispatch}, data) {
      return new Promise((resolve, reject) => {
        editPassword(data).then(res => {
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}
export default user
